import { _decorator, Button, Component, Node, tween, Vec3 } from "cc";
import { CardManager } from "./CardManager"; 
import { Card } from "./Card"; 
const { ccclass, property } = _decorator;

@ccclass("GameManager")
export class GameManager extends Component {
  @property(Button) flipButton: Button = null;

  @property(Node) flopCardNode1: Node = null;
  @property(Node) flopCardNode2: Node = null;
  @property(Node) flopCardNode3: Node = null;

  @property(Node) deckCardsNode: Node = null;

  private isFront = true;
  start() {
    const cardManager1 = this.flopCardNode1.getComponent(CardManager);
    cardManager1.hide(); // 隐藏牌的正面和背面
    const cardManager2 = this.flopCardNode2.getComponent(CardManager);
    cardManager2.hide(); // 隐藏牌的正面和背面
    const cardManager3 = this.flopCardNode3.getComponent(CardManager);
    cardManager3.hide(); // 隐藏牌的正面和背面
    this.flipButton.node.on(
      Button.EventType.CLICK,
      this.onFlipCardClicked,
      this
    );
  }

  onFlipCardClicked() {
    this.flopCard();
  }


  async flopCard() {
     // 先发完所有牌
    await this.showCardWithAnim(this.flopCardNode1, 1, 0);
    await this.showCardWithAnim(this.flopCardNode2, 2, 0.1);
    await this.showCardWithAnim(this.flopCardNode3, 3, 0.1);

    // 所有牌发完后依次翻牌
    await this.flipCardWithDelay(this.flopCardNode1, 0);
    await this.flipCardWithDelay(this.flopCardNode2, 0.1);
    await this.flipCardWithDelay(this.flopCardNode3, 0.1);
    
  }

  async showCardWithAnim(
    cardNode: Node,
    cardNumber: number,
    delay: number
  ): Promise<void> {
    return new Promise((resolve) => {
      const cardManager = cardNode.getComponent(CardManager);
      const card = new Card(cardNumber);
      cardManager.setCard(card);

      // 1. 初始化牌为背面
      cardManager.showBack();

      // 2. 动画移动 + 延迟
      const startPos = this.deckCardsNode.getPosition(); // 获取牌堆位置
      const targetPos = cardNode.getPosition(); // 获取目标位置

      cardNode.setPosition(startPos);

      // 3. 延迟 + 移动 + 翻牌
      tween(cardNode)
        .delay(delay) // 延迟
        .to(0.3, { position: targetPos }) // 发牌移动动画
        .call(() => {
          // 翻牌动画
        //   cardManager.flipToFront();
          resolve(); // 告知动画结束，继续下一张
        })
        .start();
    });
  }

  async flipCardWithDelay(cardNode: Node, delay: number): Promise<void> {
    return new Promise((resolve) => {
        const cardManager = cardNode.getComponent(CardManager);
        
        tween(cardNode)
            .delay(delay)
            .call(() => {
                cardManager.flipToFront();
                resolve();
            })
            .start();
    });
}
}
